from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from write_excel_report_data import write_excel_table
'''
PPT生成模块
'''
class PPTGenerator:
    def __init__(self, template_path=None):
        if template_path:
            self.prs = Presentation(template_path)
        else:
            self.prs = Presentation()
            
    def add_cover_slide(self, title, subtitle):
        """添加封面幻灯片"""
        slide_layout = self.prs.slide_layouts[0]  # 假设第一种布局是标题幻灯片
        slide = self.prs.slides.add_slide(slide_layout)
        title_placeholder = slide.shapes.title
        subtitle_placeholder = slide.placeholders[1]
        
        title_placeholder.text = title
        subtitle_placeholder.text = subtitle
        
    def add_deviation_table_slide(self, table_data, items_per_page=15):
        """添加偏差请求表幻灯片"""
        chunks = [table_data[i:i + items_per_page] for i in range(0, len(table_data), items_per_page)]

        for chunk in chunks:
            slide_layout = self.prs.slide_layouts[6]
            slide = self.prs.slides.add_slide(slide_layout)
            write_excel_table(slide,chunk)
        
        return slide
        
    def add_image_slide(self, image_path, dimension_label):
        """添加图片幻灯片"""
        slide_layout = self.prs.slide_layouts[5]  # 空白幻灯片
        slide = self.prs.slides.add_slide(slide_layout)
        
        # 添加标题
        title = slide.shapes.title
        title.text = "Dimension Measurement"
        title.text_frame.paragraphs[0].font.size = Pt(24)
        title.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
        
        # 添加图片
        left = Inches(1)
        top = Inches(1.5)
        pic = slide.shapes.add_picture(image_path, left, top)
        
        # 调整图片大小
        pic.width = Inches(8)
        pic.height = Inches(5)
        
        # 添加尺寸标号
        txBox = slide.shapes.add_textbox(Inches(0.5), top, width=Inches(1), height=Inches(0.5))
        p = txBox.text_frame.add_paragraph()
        p.text = dimension_label
        p.font.name = 'Arial'
        p.font.size = Pt(20)
        p.font.bold = True
        
        return slide
        
    def save_presentation(self, output_path):
        """保存PPT"""
        self.prs.save(output_path)
        print(f"PPT saved to {output_path}")